import pymssql
import time
from utils.excel import exportToXlsxFromTupleList, exportToXlsFromTupleList


# 从mssql中获取数据
def get_data_from_mssql(server, user, pwd, db, sql):
    conn = pymssql.connect(server=server, user=user, password=pwd, database=db)
    cursor = conn.cursor()

    cursor.execute(sql)
    # rows
    rows = cursor.fetchall()
    # columns
    # name, type_code, display_size, internal_size, precision, scale, null_ok
    description = cursor.description
    header = []
    for item in description:
        header.append(item[0])

    conn.close()
    return (header, rows)


#
server = ''
user = ''
password = ''
database = ''
sql = """

"""

max_count_xls = 65535
data = get_data_from_mssql(server, user, password, database, sql)
columns = data[0]
rows = data[1]

print('start to export excel')
start = time.perf_counter()
if max_count_xls > len(rows):
    exportToXlsFromTupleList(columns, rows)
else:
    exportToXlsxFromTupleList(columns, rows)
finish = time.perf_counter()

print("exported successfully and used ", finish - start, "s")
